# -*- coding: utf-8 -*-

import os
import yaml, pyaml
from log.logger import logger
from collections import OrderedDict


def yaml_load(yfile, Loader=yaml.Loader, object_pairs_hook=OrderedDict, all=False):
    if os.path.exists(yfile):
        class OrderedLoader(Loader):
            pass
        def construct_mapping(loader, node):
            loader.flatten_mapping(node)
            return object_pairs_hook(loader.construct_pairs(node))
        OrderedLoader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, construct_mapping)

        try:
            with open(yfile, 'r') as yaml_file:
                if all:
                    obj = [i for i in yaml.load_all(yaml_file, Loader=OrderedLoader)]
                else:
                    obj = yaml.load(yaml_file, Loader=OrderedLoader)
            #logger.info("Load [{0}] to python object [{1}] successfully!".format(yfile, obj))
        except Exception, e:
            obj = None
            logger.error("Load [{0}] to python object failed: [{1}]".format(yfile, e))
    else:
        obj = None
        logger.error("Load [{0}] to python object failed! Yaml file [{0}] do not exist!".format(yfile))

    return obj


def yaml_dump(obj, yfile, sort_dicts=True):
    try:
        with open(yfile, 'w') as yaml_file:
            pyaml.dump(obj, yaml_file, vspacing=[1], string_val_style='\'', sort_dicts=sort_dicts)
        #logger.info("Dump [{0}] to yaml file [{1}] successfully!".format(obj, yfile))
    except Exception as e:
        logger.error("Dump [{0}] to yaml file [{1}] failed: [{2}]".format(obj, yfile, e))

